export function formatDate(date, fmt = 'yyyy年MM月dd日') {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + '').substr(4 - RegExp.$1.length)
    );
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + '';
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : padLeftZero(str)
      );
    }
  }
  return fmt;
}
function padLeftZero(str) {
  return ('00' + str).substr(str.length);
}

export function formatDateTime(date, format = 'yyyy-MM-dd') {
  try {
    // 如果传入的是字符串或时间戳，尝试转换为 Date 对象
    if (!(date instanceof Date)) {
      date = new Date(date);
    }

    // 验证是否为有效日期
    if (isNaN(date.getTime())) {
      throw new Error('Invalid date');
    }

    const year = date.getFullYear();
    const month = date.getMonth() + 1; // 0-11 => 1-12
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();
    const millisecond = date.getMilliseconds();

    // 补零函数
    const pad = (num, len = 2) => String(num).padStart(len, '0');

    // 替换格式字符串
    return format
      .replace(/yyyy/g, year)
      .replace(/MM/g, pad(month))
      .replace(/M/g, month)
      .replace(/dd/g, pad(day))
      .replace(/d/g, day)
      .replace(/HH/g, pad(hour))
      .replace(/mm/g, pad(minute))
      .replace(/ss/g, pad(second))
      .replace(/SSS/g, pad(millisecond, 3));
  } catch (error) {
    console.error(error);
  }
}
